# preshrunk-cotton
# Copyright (C) 2010, 2011 Approximatrix, LLC
# http://code.google.com/p/preshrunk-cotton/
# http://approximatrix.com/
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# A full version of the license terms is available in LICENSE.

import sys
import os.path
import os
import shutil

import textile

class TextileProcessor:
    """Class for controlling the processing of a directory containing textile
    files into an equivalent directory tree containing html files generated
    via the textile module.  Textile files in the source tree should be named
    with the '.textile' extension."""

    def __init__(self, inputdir, outputdir=None):
        """Creates a new TextileProcessor object, capable of converting a
        textile-containing directory tree into an equivalent html-containing
        directory tree.  The output directory can be specified either here,
        when the to_html() method is called, or not at all."""

        self.inputdir = inputdir
        self.outputdir = outputdir

    def to_html(self,outputdir=None):
        """Processes the directory tree specified in the constructor, generating
        an equivalent directory tree with textile files replaced with the equivalent
        html files.  Textile inputs should be marked with a '.textile' extension.
        The target directory can be specified here or in the constructor.

        This routine does deviate from tradition textile processing slightly.  In
        particular, proper <html> and <body> flags are wrapped around the textile
        processing results.  Also, the first occurence of an "h1." header is used
        as the page's title.
        """
        if outputdir:
            self.outputdir = outputdir

        if not self.outputdir:
            self.outputdir = self.inputdir

        for (dirname, directories, files) in os.walk(self.inputdir):

            newdir = dirname.replace(self.inputdir, self.outputdir, 1)

            # Skip this directory if it starts with a "."
            rel = dirname.replace(self.inputdir, "", 1)
            if len(rel) >= 1:
                if rel.find(os.sep+'.') != -1 or rel[0] == '.':
                    continue

            if os.path.basename(dirname).startswith('.'):
                continue

            if not os.path.exists(newdir):
                os.mkdir(newdir)

            for f in files:

                title = None

                base,ext = os.path.splitext(f)
                if len(ext) == 0:
                    ext = "not important"

                if ext[1:] == 'textile':

                    fp = open(os.path.join(dirname, f), 'rb')
                    inbytes = fp.read()
                    intext = None
                    try:
                        intext = inbytes.decode('utf-8')
                    except UnicodeDecodeError:
                        intext = inbytes.decode('latin-1')
                        
                    fp.close()
                    outtext = textile.textile(intext)

                    # Find a title by searching for the first "h1." line
                    for line in intext.split('\n'):
                        if line.lstrip().startswith('h1'):
                            end_header = line.find('.')
                            if end_header > 0 and end_header+1 < len(line):
                                title = line[end_header+1:]
                                title = title.strip()
                                break

                    fp = open(os.path.join(newdir,base+os.extsep+'html'),'w')
                    fp.write("<html>")
                    if title:
                        fp.write("<title>")
                        fp.write(title)
                        fp.write("</title>")
                    fp.write("<body>\n")
                    fp.write(outtext)
                    fp.write("</body></html>\n")
                    fp.close()

                else:
                    #try:
                    if os.path.isfile(os.path.join(dirname, f)):
                        if not f.startswith('.'):  # Skip files starting with a "."
                            shutil.copyfile(os.path.join(dirname, f), 
                                            os.path.join(newdir, f))
                    #except:
                    #    pass
